#include <stdio.h>
#include <stdlib.h>

#include "buffer.h"
#include "window.h"

#define BUF_SIZE 4096

int file_open(const char *path)
{
    FILE *file = fopen(path, "r");
    char data[BUF_SIZE + 1];

    if (file == NULL)
	return -1;

    buf_create_buf_noundo(0);
    while (fgets(data, BUF_SIZE + 1, file)) {
	int len = buf_inserts_noundo(current_window->buf, data, current_window->buf->len);
	if (len > 0 && len <= BUF_SIZE) {
	    if (data[len - 1] == '\n') {
		buf_delete_noundo(current_window->buf, len - 1, len);
		buf_create_buf_noundo(current_window->buf->len);
	    }
	} else {
	    return -1;
	}
    }
    fclose(file);
    return 0;
}

int file_save(const char *path)
{
    FILE *file = fopen(path, "w");
    buf_t *buf = buf_head_buf();

    if (file == NULL)
	return -1;

    while (buf != NULL) {
	int i = fputs(buf->data, file);
	if (i < 0)
	    return -1;
	fputc('\n', file);
	buf = buf_next(buf);
    }

    fclose(file);
    return 0;
}
